package com.yunao.web.controller;

import com.yunao.commons.Exception.YunaoException;
import com.yunao.commons.enums.ResultEnum;
import com.yunao.commons.enums.UserTypeEnum;
import com.yunao.commons.utils.ResultVOUtil;
import com.yunao.commons.vo.ResultVO;
import com.yunao.entity.Subject;
import com.yunao.entity.Trade;
import com.yunao.entity.User;
import com.yunao.service.SubjectService;
import com.yunao.service.TradeService;
import com.yunao.service.UserService;
import com.yunao.web.annotation.UserLoginToken;
import com.yunao.web.convert.UserForm2UserConverter;
import com.yunao.web.form.UserForm;
import com.yunao.web.utils.TokenUtil;
import javafx.scene.SubScene;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user/user/")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SubjectService subjectService;

    @GetMapping("/getOrganByUser")
    public ResultVO getOrganByUser(){
        User userInfo =  TokenUtil.getTokenUser(userService);
        return ResultVOUtil.success(userInfo.getOrganId());
    }

    @GetMapping("/getCurrentUser")
    public ResultVO getCurrentUser(){
        User userInfo =  TokenUtil.getTokenUser(userService);
        userInfo.setPassword("");
        return ResultVOUtil.success(userInfo);
    }

    @GetMapping("/list")
    public ResultVO list(@RequestParam Integer organId){
        List<User> userList = userService.findByOrgan(organId);
        return ResultVOUtil.success(userList);
    }

    public ResultVO listbak(@RequestParam(required = false) Integer organId){
        User user = TokenUtil.getTokenUser(userService);
        if (user.getRole()==UserTypeEnum.COMMON_USER.getCode()){
            return ResultVOUtil.error(ResultEnum.USER_ROLE_ERROR);
        }else if (user.getRole()==UserTypeEnum.ORGAN_MANAGE.getCode()){
            return ResultVOUtil.success(userService.findByOrgan(user.getOrganId()));
        }else {
            if (StringUtils.isEmpty(organId+"")||organId==0){
                return ResultVOUtil.error(ResultEnum.ORGAN_NOT_EXIET);
            }
            List<User> userList = userService.findByOrgan(organId);
            return ResultVOUtil.success(userList);
        }
    }

    @GetMapping("/findone")
    public ResultVO findone(@RequestParam Integer userId){
        User user = userService.findOne(userId);
        if (user==null){
            throw new YunaoException(ResultEnum.USER_NOT_EXIST);
        }
        return ResultVOUtil.success(user);
    }

    @PostMapping("/save")
    @Transactional
    public ResultVO save(@Valid UserForm userForm,
                         BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            log.error("【创建用户】参数不正确");
            throw new YunaoException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        if (userService.findByUsername(userForm.getName())!=null){
            throw new YunaoException(ResultEnum.USER_EXIST);
        }
        User user = UserForm2UserConverter.convert(userForm);
        if (user.getOrganId()==null||user.getOrganId()==0){
            User cucrentUser = TokenUtil.getTokenUser(userService);
            user.setOrganId(cucrentUser.getOrganId());
        }
        userService.save(user);

        //创建用户之后，根据用户的地域和行业创建两个专题,根据二级行业创建三个专题
        saveSubjectByUser(user,userForm);

        return ResultVOUtil.success();
    }

    @PostMapping("/edit")
    @Transactional
    public ResultVO edit(UserForm userForm){
        User user = userService.findOne(userForm.getId());
        if (user == null) {
            throw new YunaoException(ResultEnum.USER_NOT_EXIST);
        }
        user = UserForm2UserConverter.convert(userForm,user);
        if (user.getOrganId()==null||user.getOrganId()==0){
            User cucrentUser = TokenUtil.getTokenUser(userService);
            user.setOrganId(cucrentUser.getOrganId());
        }
        userService.save(user);

        return ResultVOUtil.success();
    }


    @UserLoginToken
    @PostMapping("/updateByOpenid")
    @Transactional
    public void update(@RequestParam("openid") String openid, @RequestParam("userid") String userid){
        userService.updateOpenidByUserid(openid,userid);
    }


    private void saveSubjectByUser(User user, UserForm userForm) {
        Subject subjectForm2= new Subject();
        subjectForm2.setSubjectName(userForm.getFirsttrade());
        subjectForm2.setParentid(0);
        subjectForm2.setSubjectQuery("");
        subjectForm2.setWord(userForm.getFirsttrade());
        subjectForm2.setUserId(user.getUserId());
        subjectForm2.setOrganId(user.getOrganId());
        subjectForm2.setSubjectType(0);
        subjectForm2.setIshome(1);
        subjectService.save(subjectForm2);
        user.setSubjectNum(user.getSubjectNum()+1);
        userService.save(user);

        if (StringUtils.isNotEmpty(userForm.getSecondtrade())){
            Subject subjectForm4= new Subject();
            subjectForm4.setSubjectName(userForm.getSecondtrade());
            subjectForm4.setSubjectQuery("");
            subjectForm4.setParentid(subjectService.findByUserAndName(user.getUserId(),userForm.getFirsttrade()).getSubjectId());
            subjectForm4.setWord(userForm.getSecondtrade());
            subjectForm4.setUserId(userService.findByUsername(user.getUsername()).getUserId());
            subjectForm4.setOrganId(user.getOrganId());
            subjectForm4.setSubjectType(0);
            subjectForm4.setIshome(1);
            subjectService.save(subjectForm4);
            user.setSubjectNum(user.getSubjectNum()+1);
            userService.save(user);
        }

        Subject subjectForm= new Subject();
        subjectForm.setSubjectName(userForm.getProvince());
        subjectForm.setSubjectQuery("");
        if (StringUtils.isNotEmpty(userForm.getCity()))
            subjectForm.setSubjectLocaltion(userForm.getProvince()+":"+userForm.getCity());
        else
            subjectForm.setSubjectLocaltion(userForm.getProvince());
        subjectForm.setWord(userForm.getProvince());
        subjectForm.setParentid(0);
        subjectForm.setUserId(userService.findByUsername(user.getUsername()).getUserId());
        subjectForm.setOrganId(user.getOrganId());
        subjectForm.setSubjectType(0);
        subjectForm.setIshome(1);
        subjectService.save(subjectForm);
        user.setSubjectNum(user.getSubjectNum()+1);
        userService.save(user);

    }
    @UserLoginToken
    @GetMapping("/delete")
    public ResultVO delete(Integer userId){
        userService.delete(userId);
        return ResultVOUtil.success();
    }

}
